<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/10/30 14:40
 */


namespace App\Http\Controllers;


use App\Component\WXBizDataCrypt;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $code          = $request->input('code');
        $encryptedData = $request->input('encryptedData');
        $iv            = urldecode($request->input('iv'));
        $session       = $this->code2sessionKey($code);
        $pc            = new WXBizDataCrypt(env('MINI_APPID'), $session['session_key']);
        $errCode       = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $data            = json_decode($data);
            $user            = User::query()->firstOrNew(['open_id' => $data->openId]);
            $user->nick_name = $data->nickName;
            $user->gender    = $data->gender;
            $user->city      = $data->city;
            $user->avatar    = $data->avatarUrl;
            if ($user->isDirty()) {
                $user->save();
            }

            return $this->responseSuccess('登录成功', ['open_id' => $data->openId]);
        } else {
            return $this->responseFail('登录失败,请重新登录');
        }
    }

    /**
     * 获取openId
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getOpenId(Request $request)
    {
        $code    = $request->input('code');
        $session = self::code2sessionKey($code);

        return $this->responseSuccess('', $session);
    }

    /**
     * code 换取session_key
     *
     * @param string $code
     *
     * @return mixed
     */
    protected function code2sessionKey($code = '')
    {
        $url    = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . env('MINI_APPID') . '&secret=' . env('MINI_APPSECRET') . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = file_get_contents($url);

        return json_decode($result, true);
    }
}